//
//  ComposeViewController.swift
//  Status
//
//  Created by 花轮 on 15/5/22.
//  Copyright (c) 2015年 花轮. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController,UITextViewDelegate {

    @IBAction func close(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @IBOutlet weak var toolbarBottomContraint: NSLayoutConstraint!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var sendButton: UIBarButtonItem!
    @IBOutlet weak var rongqiHeightContraint: NSLayoutConstraint!
    
    var picVc: PictViewController?
    
    @IBAction func pictureClick(sender: AnyObject)
    {
        rongqiHeightContraint.constant = UIScreen.mainScreen().bounds.height / 3
        textView.endEditing(true)
    }
    @IBAction func sendClick()
    {
        let params = ["access_token" : sharedUserAccount!.access_token,
            "status" : textView.text]
        
        if picVc?.imageList.count > 0 {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let image = picVc!.imageList[0]
            let data = UIImagePNGRepresentation(image)
            
            let dataList = ["haha" : data]
            
            NetworkTools.uploadPict(urlString, fieldName: "pic", dataList: dataList, parameters: params)
            
            self.dismissViewControllerAnimated(true, completion: nil)

            return
        }
        
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        NetworkTools.requestJSON(.POST, URLStr: urlStr, parameters: params) { (JSON) -> () in
            println(JSON)
            
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
   
    lazy var textField: UITextField = {
        let t = UITextField()
        t.frame = CGRectMake(5, 8, 0, 0)
        t.text = "请输入文字。。。"
        t.font = UIFont.systemFontOfSize(14)
        t.textColor = UIColor.lightGrayColor()
        self.textView.addSubview(t)
        return t
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        println(self.childViewControllers)
        for vc in childViewControllers {
            if vc is UICollectionViewController
            {
                picVc = vc as? PictViewController
                break
            }
        }
        
     nameLabel.text = sharedUserAccount?.name
        textField.sizeToFit()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillHideNotification, object: nil)
        rongqiHeightContraint.constant = 0
    }
    
    override func viewWillAppear(animated: Bool) {
        if picVc?.imageList.count == 0
        {
            textView.becomeFirstResponder()
        }
    }
    override func viewWillDisappear(animated: Bool) {
        view.endEditing(true)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func keyboardWillChangeFrame(n: NSNotification)
    {
//        println(n)
        let d = n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        /*
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 252}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 541}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 793}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 415}, {375, 252}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 252}}";
        
        
        userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 252}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 793}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 541}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 252}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 415}, {375, 252}
        */
        var height:CGFloat = 0;
        
        if n.name == UIKeyboardWillChangeFrameNotification
        {
            let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
            height = rect.height
        }
        
        if picVc?.imageList.count == 0
        {
            rongqiHeightContraint.constant = 0
        }
        
       UIView.animateWithDuration(d, animations: { () -> Void in
        self.toolbarBottomContraint.constant = height
        self.view.layoutIfNeeded()
       })
    }
    
    
    // MARK: - textView的代理方法
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        view.endEditing(true)
//        textView.resignFirstResponder()
    }
    func textViewDidChange(textView: UITextView) {
//        println(__FUNCTION__)
        textField.hidden = !textView.text.isEmpty
        sendButton.enabled = !textView.text.isEmpty
//        println("textview \(textView.text)")

        var text = textView.text as NSString
        if text.length > 10 {
            textView.text = text.substringToIndex(10)
        }
    }
    
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
//        println("textview \(textView.text)")
//        println("range \(range)")
//        println("text \(text)")
        if text == "\n"
        {
            sendClick()
        }
        if count(textView.text) + count(text) > 10 {
            return false
        }
        return true
    }
}
